package util

import (
	"encoding/json"
	"flag"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"

	"github.com/go-kit/log"
	"github.com/go-kit/log/level"
	"github.com/pelletier/go-toml"
	"gopkg.in/natefinch/lumberjack.v2"
)

var Sconf ServerConfig
var Logger log.Logger
var (
	ProConfig = flag.String("pconfig", "proc.config", "config of processes")
	SrvConfig = flag.String("sconfig", "server.config", "config of server")
	// localHttpPort int
)

func init() {
	flag.Parse()
	dirPath, err := os.Executable()
	if err != nil {
		panic(err)
	}
	// fmt.Println(filepath.Join(path.Dir(dirPath), "process_monitor.log"))
	Logger = log.NewLogfmtLogger(&lumberjack.Logger{
		Filename:   filepath.Join(path.Dir(dirPath), "process_monitor.log"),
		MaxSize:    200,
		MaxBackups: 3,
		MaxAge:     7,
		Compress:   false,
	})
	Logger = log.With(Logger, "ts", log.DefaultTimestamp)
	Logger = log.With(Logger, "caller", log.DefaultCaller)
	serverConfigFile, err := AbsPath(*SrvConfig)
	if err != nil {
		level.Error(Logger).Log("error", err)
		panic(err)
	}
	Sconf = ServerConfig{}
	b, err := ioutil.ReadFile(serverConfigFile)
	if err != nil {
		panic(err)
	}
	err = toml.Unmarshal(b, &Sconf)
	if err != nil {
		panic(err)
	}
}

// ReadProcessConfig 读取进程信息的配置文件
func ReadProcessConfig(proConfig string) map[string]int {
	//将配置文件的json内容转为map
	procMap := make(map[string]int)
	data, err := ioutil.ReadFile(proConfig)
	if err != nil {
		panic(err)
	}
	err = json.Unmarshal(data, &procMap)
	if err != nil {
		panic(err)
	}
	return procMap
}

type ServerConfig struct {
	Server   Server `toml:"server"`
	Rabbitmq Mq     `toml:"rabbitmq"`
}
type Server struct {
	Ipaddr  string `toml:"ipaddr"`
	Project string `toml:"project"`
	Team    string `toml:"team"`
	Nic     string `toml:"nic"`
	Altype  string `toml:"altype"`
	Cluster string `toml:"cluster"`
	Name    string `toml:"name"`
	Call    string `toml:"call"`
}
type Mq struct {
	User  string `toml:"user"`
	Pass  string `toml:"pass"`
	Url   string `toml:"url"`
	Queue string `toml:"queue"`
}
